import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class TreeNode2 {
           int val;
           TreeNode2 left;
           TreeNode2 right;
           TreeNode2() {}
           TreeNode2(int val) { this.val = val; }
           TreeNode2(int val, TreeNode2 left, TreeNode2 right) {
                 this.val = val;
                 this.left = left;
                 this.right = right;
      }
}
class Solution {

    int preIndex = 0;
    public TreeNode2 buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length-1);
    }

    private TreeNode2 buildTreeChild(int[] preorder, int[] inorder, int inbegin, int inend) {
        // 递归出口
        if(inbegin > inend) {
            return null;
        }
        //根 左 右
        TreeNode2 root = new TreeNode2(preorder[preIndex]);
        int rootIndex = findIndex(inorder, inbegin, inend, preorder[preIndex]);
        preIndex++;

        root.left = buildTreeChild(preorder, inorder, inbegin, rootIndex-1);
        root.right = buildTreeChild(preorder, inorder, rootIndex+1, inend);

        return root;

    }

    private int findIndex(int[] inorder, int inbegin, int inend, int key) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

    /*public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root != null) {
            queue.offer(root);
        }
        while(!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            while(size != 0) {
                TreeNode top = queue.poll();
                list.add(top.val);
                if(top.left != null) {
                    queue.offer(top.left);
                }
                if(top.right != null) {
                    queue.offer(top.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }*/

    /*public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if(root != null) {
            queue.offer(root);
        }
        while(!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            while(size != 0) {
                TreeNode top = queue.poll();
                list.add(top.val);
                if(top.left != null) {
                    queue.offer(top.left);
                }
                if(top.right != null) {
                    queue.offer(top.right);
                }
                size--;
            }
            ret.add(0, list);
        }
        return ret;
    }*/
}